<template>
  <div style="width: 200px">
    <button @click="toggleBox">{{ isVisible ? '隐藏' : '显示' }} 盒子</button>
    <div
      class="box"
      :class="{ fadeIn: isVisible, fadeOut: !isVisible }"
      v-if="isVisible || isFading"
    >
      这是一个盒子
    </div>
  </div>
</template>

<script>
export default {
  name: 'fadeView',
  data() {
    return {
      isVisible: false,
      isFading: false,
    }
  },
  methods: {
    toggleBox() {
      if (this.isVisible) {
        this.isFading = true
        setTimeout(() => {
          this.isVisible = false
          this.isFading = false
        }, 500) // 动画时长需与 CSS 动画一致
      } else {
        this.isVisible = true
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.box {
  width: 200px;
  height: 100px;
  background-color: #3498db;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 20px 0;
  border-radius: 5px;
  opacity: 0; /* 初始透明度 */
  animation-duration: 0.5s; /* 动画时长 */
}

.fadeIn {
  animation-name: fadeIn;
  animation-fill-mode: forwards; /* 保持最终状态 */
}

.fadeOut {
  animation-name: fadeOut;
  animation-fill-mode: forwards; /* 保持最终状态 */
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}
</style>
